package com.wpp.algorithm.lagou.part1.lesson2;
/**
 * @author wpp25
 * @date 2021/5/1 11:04
 * @description：
 * 给你两个二进制字符串，返回它们的和（用二进制表示）。
 * 输入为 非空 字符串且只包含数字 1 和 0
 */
public class Part2_1 {

    public static void main(String[] args) {
        System.out.println(addBinary("00101111","011101"));
    }

    /**
     * @param a   0011 0010
     * @param b    100 0011
     * @return
     */
    public static String addBinary(String a, String b) {
        // 在此处写入代码
        char[] chars1 = a.toCharArray();
        char[] chars2 = b.toCharArray();

        int betterLength = Math.max(chars1.length, chars2.length);

        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for (int i = 0; i < betterLength; i++) {
            carry += i < chars1.length ? convert(chars1[chars1.length - 1 - i]) : 0;
            carry += i < chars2.length ? convert(chars2[chars2.length - 1 - i]) : 0;
            sb.append(carry % 2);
            carry = carry / 2;
        }
        if (carry > 0) {
            sb.append(1);
        }
        sb = sb.reverse();
        return sb.toString();

    }
    private static Integer convert(char ch) {
        return Integer.valueOf(String.valueOf(ch));
    }

}




